package ar.tuc.unsta.campus.weather.unstaWeatherUpload.controller;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;

import javax.swing.JFileChooser;

import ar.tuc.unsta.campus.weather.unstaWeatherUpload.model.FileUploaderModel;
import ar.tuc.unsta.campus.weather.unstaWeatherUpload.view.FileUploaderView;


public class FileUploaderController implements ActionListener{

	FileUploaderView fileUploaderView = null;
	FileUploaderModel fileUploaderModel = null;
	
	public FileUploaderController(FileUploaderView view, FileUploaderModel model){
		this.fileUploaderView = view;
		this.fileUploaderModel = model;
		addListeners();
	}
		
	/**
	 * Add listeners to the view components so they perform actions
	 */
	private void addListeners(){
		fileUploaderView.getBtnBrowse().addActionListener(this);
		fileUploaderView.getBtnSubir().addActionListener(this);
		fileUploaderView.getBtnCancelar().addActionListener(this);
	}

	/**
	 * Implemented method from interface
	 */
	public void actionPerformed(ActionEvent e) {
		if(e.getSource() == fileUploaderView.getBtnBrowse()){
			JFileChooser fc = fileUploaderView.getFileChooser();
			if(fc == null)
				fc = new JFileChooser();
			int returnVal = fc.showOpenDialog(null);
			
	        if (returnVal == JFileChooser.APPROVE_OPTION) {
	        	File file = fc.getSelectedFile();
	        	fileUploaderView.getFilePathTextField().setText(file.getAbsolutePath());
	        }
		} else if(e.getSource() == fileUploaderView.getBtnSubir()){
			File file = new File(fileUploaderView.getFilePathTextField().getText());
			fileUploaderView.getBtnSubir().setEnabled(false);
			fileUploaderView.getBtnBrowse().setEnabled(false);
			fileUploaderModel.listenToFile(file);
		} else if(e.getSource() == fileUploaderView.getBtnCancelar()){
			fileUploaderModel.stopListening();
			fileUploaderView.getBtnSubir().setEnabled(true);
		}
	}
	
	
}
